# from fastapi import APIRouter, UploadFile, File
# from app.schemas import video_schema
from app.services import video_service
from fastapi import APIRouter, File, UploadFile
import ffmpeg
import os
import asyncio

router = APIRouter()

@router.post("/videos/upload")
async def upload_video(video: UploadFile = File(...)):
    return await video_service.upload_video(video)

@router.get("/videos/{video_id}")
async def get_video(video_id: int):
    return await video_service.get_video(video_id)

@router.post("/ffmpeg-api/convert_video")
async def convert_video(video: UploadFile = File(...)):
    try:
        # 获取当前工作目录作为临时文件保存的基础路径，你也可以指定其他特定目录
        base_path = os.getcwd()
        # 构建临时文件保存路径，这里使用原文件名，也可按需修改文件名等
        temp_file_path = os.path.join(base_path, "temp", video.filename)
        os.makedirs(os.path.dirname(temp_file_path), exist_ok=True)

        with open(temp_file_path, 'wb') as f:
            f.write(video.file.read())

        # 在这里可以使用ffmpeg-python对临时保存的视频文件进行处理，例如格式转换等
        # 以下是简单示例，输出文件名添加_converted后缀表示转换后的文件
        output_video_path = os.path.join(base_path, "temp", os.path.splitext(video.filename)[0] + '.avi')
        input_video = ffmpeg.input(temp_file_path)
        output_video = ffmpeg.output(input_video, output_video_path)
        await asyncio.sleep(1)  # 模拟异步耗时操作
        ffmpeg.run(output_video)

        return {"message": "视频上传并处理成功"}
    except Exception as e:
        return {"message": f"视频上传或处理出现问题: {str(e)}"}
    finally:
        # 无论是否成功，删除临时文件（上传的原始文件和处理后的文件，若存在）
        if os.path.exists(temp_file_path):
            os.remove(temp_file_path)
        if os.path.exists(output_video_path):
            os.remove(output_video_path)